<?php
/**
 * 微信端访问
 */
namespace Home\Controller;

use Common\Controller\BaseController;

class IndexController extends BaseController
{
    // 主页应用路由表
    const ROUTE = array(
        8 => self::ROOT . '/index.php/home/exception/index',
        9 => self::ROOT . '/index.php/home/scheme/index',
    );

    /**
     * 获取用户的身份信息
     */
    public function _initialize()
    {
        parent::_initialize();

        // 携带cookie访问应用时，则不再向微信发起身份认证
        if ($_SESSION['user_info']) return true;

        // 微信返回身份认证访问时，将获取的用户信息，写入session
        if (I('code') && I('state')) {
            $user_id = self::$we->getUserId(I('code'), I('state'));

            session_start();
            $_SESSION = self::$we->getUserInfo($user_id['UserId']);
            return true;
        }
    }

    /**
     * 入口访问审查
     * 禁止未携带应用id的用户访问路由入口
     * 禁止没有session的用户访问应用入口
     */
    public function _before_index() {
        I('app_id') || $_SESSION['userid'] ? '' : exit;
    }

    /**
     * 主页应用路由入口，重定向到微信服务器
     * OAuth2身份验证
     */
    public function index()
    {
        $app_id       = I('app_id');
        $url          = self::ROUTE[$app_id];
        $redirect_uri = urlencode($url);
        $url_code     = 'https://open.weixin.qq.com/connect/oauth2/authorize';
        $url_code    .= '?appid=' . self::CORP_ID;
        $url_code    .= '&redirect_uri=' . $redirect_uri;
        $url_code    .= '&response_type=code&scope=SCOPE';
        $url_code    .= '&state=' . $app_id;
        $url_code    .= '#wechat_redirect';

        header('Location: ' . $url_code);
    }

    /**
     * 发送微信消息
     */
    protected function text($touser, $text)
    {
        $data = array(
            'touser'    => $touser,
            'agentid'   => 0,
            'msgtype'   => 'text',
            'text'      => array('content' => $text)
        );

        $json = self::$we->sendMessage($data);
        return $json['errmsg'];
    }

    public function check()
    {
        task();
    }

}
